// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init()

const TcbRouter = require('tcb-router')

const db = cloud.database()

const blogCollection = db.collection('blog')

const blogCommentCollection = db.collection('blog-comment')

const MAX_LIMIT = 100

const _ = db.command

// 云函数入口函数
exports.main = async(event, context) => {
  const app = new TcbRouter({
    event
  })

  app.router('deleteAllBlog', async(ctx, next) => {
    try {
      ctx.body = await blogCollection.where({
        '_id': _.neq('')
      }).remove()
    } catch (e) {
      console.error(e)
    }
  })

  app.router('deleteAllBlogComment', async(ctx, next) => {
    try {
      ctx.body = await blogCommentCollection.where({
        '_id': _.neq('')
      }).remove()
    } catch (e) {
      console.error(e)
    }
  })

  // blog list
  app.router('list', async(ctx, next) => {
    const keyword = event.keyword

    let w = {}
    if (keyword.trim() != '') {
      w = {
        content: db.RegExp({
          regexp: keyword,
          options: 'i'
        })
      }
    }

    let blogbody = await blogCollection.where(w).skip(event.start).limit(event.count)
      .orderBy('createTime', 'desc').get().then((res) => {
        return res.data
      })
    ctx.body = blogbody
  })

  // 博客详情
  app.router('detail', async(ctx, next) => {
    let blogId = event.blogId
    // 详情查询
    let detail = await blogCollection.where({
      _id: blogId
    }).get().then((res) => {
      return res.data
    })
    // 评论查询
    const countResult = await blogCommentCollection.count()
    const total = countResult.total
    let commentList = {
      data: []
    }

    if (total > 0) {
      const batchTimes = Math.ceil(total / MAX_LIMIT)
      const promiseTasks = []
      for (let i = 0; i < batchTimes; i++) {
        let promise = blogCommentCollection
          .skip(i * MAX_LIMIT)
          .limit(MAX_LIMIT)
          .where({
            blogId
          }).orderBy('createTime', 'desc').get()

        promiseTasks.push(promise)
      }

      if (promiseTasks.length > 0) {
        // 等待所有任务执行完成
        commentList = (await Promise.all(promiseTasks)).reduce((acc, cur) => {
          return {
            data: acc.data.concat(cur.data)
          }
        })
      }
    }
    ctx.body = {
      commentList,
      detail,
    }

  })

  // 查询我的博客
  const wxContext = cloud.getWXContext()
  app.router('getMyBlog', async(ctx, next) => {
    const keyword = event.keyword
    let blogbody = await blogCollection.where({
      _openid: wxContext.OPENID
    })
      .skip(event.start).limit(event.count)
      .orderBy('createTime', 'desc')
      .get()
      .then((res) => {
        return res.data
      })
    ctx.body = blogbody
  })

  return app.serve()
}